﻿using AntdUI;
using CKS.Core.Framework;
using CKS.PLC.Core;
using CKS.PLC.Core.Cache;
using CKS.PLC.Core.Event;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZR.Infrastructure;
using ZR.Model.Models.ProductionControl;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;


namespace CKS.MES.Server
{
    public partial class MainForm2 : AntdUI.Window
    {
        bool firstRun = true;
        public MainForm2()
        {
            InitializeComponent();
            //AntdUI.Config.Mode = AntdUI.TMode.Dark;
            //AntdUI.Config.IsDark = true;

            txtLog.ReadOnly = true;
            this.FormClosing += MainForm2_FormClosing;
            this.Load += MainForm2_Load;
            this.Text = "KS@MesServer";
            txtLog.AutoScroll = true;



            var IsProduct = Configs.GetValue("Product").ToBool();
            InternalApp.DebugMode = !IsProduct;

            SetProductModeButton();
            firstRun = false;
        }

        bool lastMockStatus = false; //上次模拟状态值
       
        private void SetProductModeButton()
        {
            try
            {
                if(lastMockStatus != InternalApp.DebugMode)
                {
                    if (InternalApp.DebugMode)
                    {
                        btnProductMode.Text = "当前:模拟模式";
                        btnProductMode.Type = TTypeMini.Warn;
                        EventBus.AddLog($"当前:模拟模式");
                    }
                    else
                    {
                        btnProductMode.Text = "当前:生产模式";
                        btnProductMode.Type = TTypeMini.Success;
                        EventBus.AddLog($"当前:生产模式");
                    }
                    lastMockStatus = InternalApp.DebugMode;
                    if(!firstRun)
                    {
                        var fsql = InternalApp.Fsql;
                        fsql.Delete<CksContainer>().Where(a => a.ProductMode == 2).ExecuteAffrows();
                        fsql.Delete<CksPackagingExceptionTask>().Where(a => a.ProductMode == 2).ExecuteAffrows();
                        fsql.Delete<CksPackagingTask>().Where(a => a.ProductMode == 2).ExecuteAffrows();

                    }

                }

            }
            catch (Exception)
            {

            }
        }

        private void MainForm2_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dr = AntdUI.Modal.open(new AntdUI.Modal.Config(this, "Message",
                  "Are you sure to exit")
            {
                //禁止使用键盘关闭
                Keyboard = false,
                MaskClosable = false,
                OkText = "Yes",
                CancelText = "No",
            });
            if (dr != DialogResult.OK)
            {
                e.Cancel = true;
            }
        }
        public string backendUrl = "";

        private void MainForm2_Load(object sender, EventArgs e)
        {
            AddLog("启动成功！");

            var ipAll = ToolsHelper.GetLocalIps();
            foreach (var item in ipAll)
            {
                AddLog($"本地IP {item}");
            }


            var app = InternalApp.App;
            var url = app.Urls.First();
            var u = new Uri(url);


            //pnlLeft.Width = 0;
            this.Icon = ImageToIcon(pageHeader1.Icon);

            this.StartPosition = FormStartPosition.CenterScreen;
            backendUrl = $"{u.Scheme}://localhost:{u.Port}/";
            AddLog($"本机服务地址:{backendUrl}");
            //if(!localIP.IsEmpty())
            //    AddLog($"局域网服务地址:{u.Scheme}://{localIP}:{u.Port}/");
            foreach (var localIP in ipAll)
            {
                AddLog($"局域网服务地址:{u.Scheme}://{localIP}:{u.Port}/");

            }
            txtLog.TabStop = false;
            txtLog.BorderActive = Color.Transparent;
            txtLog.BorderHover = Color.Transparent;
            IntervalWriteLog();

            Task.Run(UpdatePlcTable);


        }



        public Icon ImageToIcon(Image image)
        {
            // 创建一个与原始图像大小相同的空白图像
            Bitmap iconBitmap = new Bitmap(64, 64);
            // 使用原始图像绘制空白图像
            using (Graphics graphics = Graphics.FromImage(iconBitmap))
            {
                graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                graphics.DrawImage(image, 0, 0, 64, 64);
            }
            using (Icon icon = Icon.FromHandle(iconBitmap.GetHicon()))
            {
                // 保存图标到文件
                //using (FileStream fs = new FileStream("output.ico", FileMode.Create, FileAccess.Write))
                //{
                //    icon.Save(fs);
                //}
                // 复制Icon，因为GetHicon()在调用后会释放图标资源
                return Icon.FromHandle(icon.Handle);
            }

        }

        private void btnVisit_Click(object sender, EventArgs e)
        {
            if (!backendUrl.IsEmpty())
                System.Diagnostics.Process.Start(new ProcessStartInfo(backendUrl) { UseShellExecute = true });
        }



        private void AddLog(string msg)
        {

            EventBus.AddLog(msg);

        }

        private void IntervalWriteLog()
        {
            Task.Run(() =>
            {

                try
                {

                    int maxsize = 99;
                    SafeList<string> logs = new SafeList<string>(maxsize);

                    while (this.IsHandleCreated)
                    {
                        try
                        {
                            //InternalApp.DebugMode = !Configs.GetValue("Product").ToBool();
                            SetProductModeButton();
                            //  List<string> newlogs = new List<string>();
                            bool AddNew = false;
                            while (EventBus.logQueues.TryDequeue(out string msg))
                            {
                                logs.Add(msg);
                                AddNew = true;
                            }

                            if (AddNew)
                            {
                                var index = 0;
                                txtLog.Text = string.Join("\r\n", logs.ToList().Select(a => $"{++index} {a}"));
                                txtLog.AppendText("\r\n");
                                txtLog.AutoScroll = true;

                                if (logs.Count != maxsize)
                                {
                                    // int cursorPosition = txtLog.SelectionStart;
                                    txtLog.SelectionStart = txtLog.Text.Length; // 将光标移动到文本末尾
                                    txtLog.SelectionLength = 0; // 确保没有文本被选中
                                    txtLog.ScrollToCaret(); // 如果需要的话，将滚动条滚动到光标位置
                                }

                            }


                        }
                        catch (Exception)
                        {

                        }




                        Thread.Sleep(500);
                    }
                }
                catch (Exception ex)
                {

                }

            });



        }

        private void UpdatePlcTable()
        {
            try
            {
                while (this.IsHandleCreated)
                {
                    //获取客户端列表，绑定到UI
                    //在线状态，和心跳值。 心跳值是1 绿色，0 是黑色
                    var plcs = ServiceCommon.PlcClients.ToList();

                    plcTable.BindPlc(plcs);
                    Thread.Sleep(500);
                }
            }
            catch (Exception)
            {

            }
        }

        private void btnProductMode_Click(object sender, EventArgs e)
        {
            try
            {
                var nextDebug = !InternalApp.DebugMode;

                if (nextDebug)
                {
                }

                //提醒用户是否切换到调试模式
                DialogResult dr = AntdUI.Modal.open(new AntdUI.Modal.Config(this, "Message",
              "确认要切换模式吗")
                {
                    //禁止使用键盘关闭
                    Keyboard = false,
                    MaskClosable = false,
                    OkText = "Yes",
                    CancelText = "No",
                });
                if (dr != DialogResult.OK)
                {
                    return;
                }

                string productMode = (!nextDebug).ToString();
                Configs.SetValue("Product", productMode);
                InternalApp.DebugMode = nextDebug;
                //状态切换时，清除调试模式的数据
                
                SetProductModeButton();
            }
            catch (Exception ex)
            {
                EventBus.AddError($"切换模式发生异常：{ex.Message} {ex.StackTrace}");
            }
        }
    }
}
